/** ChickenWarrior, a Simple Java ME game developed in Gnu/Linux
  *  Copyright (C) <2008>  Maxin B. John <maxinbjohn@gmail.com>
  *
  *  This program is free software; you can redistribute it and/or modify
  *  it under the terms of the GNU General Public License as published by
  *  the Free Software Foundation; either version 3 of the License, or
  *  any later version.
  *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
  *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, see http://www.gnu.org/licenses
  *  or write to the Free Software Foundation,Inc., 51 Franklin Street,
  *  Fifth Floor, Boston, MA 02110-1301  USA
  * 
  */

package com;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.lcdui.game.LayerManager;
import javax.microedition.lcdui.game.Sprite;
import javax.microedition.midlet.*;

/**
 *
 * @author Maxin B. John <maxinbjohn@gmail.com>
 * 
 */
public class MyGameCanvas  extends GameCanvas implements Runnable{
     private static final int SPEED = 5;
     private LayerManager lm;
     //private byte lastDirection = -1;
     private SpriteAnimationTask spriteEggAnimator;
     private SpriteAnimationTask spriteChickenAnimator;
     private EggFall EggRandomMovement;
     private boolean interrupted;
     private Timer timer;
     private MyGameDesign gameDesign;
     private int eggNumber;
     private Sprite Egg;
     private Sprite Chicken;
     public MIDlet mid;
     public int canvasHeight;
     public int canvasWidth;
     
     
     public MyGameCanvas(){
            super(true);
            this.eggNumber=0;
            this.setFullScreenMode(true);
            this.init();
        }
     
    public void stop() {
        this.interrupted = true;
    }
     private void init()  {
         try{
         System.out.println("In init \n");
         this.timer = new Timer();
         this.gameDesign= new MyGameDesign(); 
         this.Egg = gameDesign.getEgg();
         this.Chicken = gameDesign.getMyChicken();
         this.Egg.defineReferencePixel(8, 8);
         this.Chicken.defineReferencePixel(8, 8);
         this.canvasHeight= this.getHeight();
         this.canvasWidth = this.getWidth();
         this.spriteEggAnimator = new SpriteAnimationTask(this.Egg, false);
         this.spriteChickenAnimator = new SpriteAnimationTask(this.Chicken, false);
         this.timer.scheduleAtFixedRate(this.spriteEggAnimator, 0, gameDesign.Eggseq001Delay);
         this.timer.scheduleAtFixedRate(this.spriteChickenAnimator, 0, gameDesign.MyChickenseq001Delay);
         this.lm = new LayerManager();
         gameDesign.updateLayerManagerForMySky(lm);
         this.EggRandomMovement = new EggFall(this, Egg);
      
         this.EggRandomMovement.setSequences(
            gameDesign.MyChickenseq001, Sprite.TRANS_NONE, 
            gameDesign.MyChickenseq001, Sprite.TRANS_NONE, 
            gameDesign.MyChickenseq001, Sprite.TRANS_NONE, 
            gameDesign.MyChickenseq001, Sprite.TRANS_NONE
            );
       
        (new Thread(EggRandomMovement)).start();
         }catch (IOException io){}
         }
     
     public boolean setEggNo(){
         this.eggNumber+=1;
         return true;
     }
     
     public int getEggNo(){
         return this.eggNumber;
       }

      /**
     * Check if sprite collides with the Chicken object
     *
     * @param sprite the sprite checked for collision with other layers
     * @return true is sprite does collide, false otherwise
     */
    public boolean spriteCollides(Sprite sprite) {
     return sprite.collidesWith(this.Chicken, true);
       }
     
     public void run(){
           System.out.println("Inside the run \n");
           Graphics g = getGraphics();
           while (!this.interrupted) {
            //check for user input
            int keyState = getKeyStates();
            if ((keyState & LEFT_PRESSED) != 0) {
                this.Chicken.setFrameSequence(gameDesign.MyChickenseq001);
                this.Chicken.setTransform(Sprite.TRANS_MIRROR);
                this.spriteChickenAnimator.backward();
                this.Chicken.move(-SPEED, 0);
                System.out.println("Left key pressed \n");
               
            }
            if ((keyState & RIGHT_PRESSED) != 0) {
                this.Chicken.setFrameSequence(gameDesign.MyChickenseq001);
                this.Chicken.setTransform(Sprite.TRANS_MIRROR);
                this.Chicken.move(SPEED, 0);
                System.out.println("Right key pressed \n");
                
            
            }
            if ((keyState & UP_PRESSED) != 0) {
                this.Chicken.setFrameSequence(gameDesign.MyChickenseq001);
                this.Chicken.setTransform(Sprite.TRANS_MIRROR);
                System.gc();
                try{
                   this.mid.notifyDestroyed();
                  }catch(Exception ex){
                 
              }
            }  
                        
            this.Chicken.setFrameSequence(gameDesign.MyChickenseq001);
            this.spriteChickenAnimator.setMoving(true);
            this.lm.paint(g, 0, 0);
            flushGraphics(0, 0, this.getWidth(), this.getHeight());
             try {
                Thread.sleep(200);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
         }
     }
     
/**
     * Animates a sprite.
     */
  private class SpriteAnimationTask extends TimerTask {

        private boolean moving = false;
        private boolean forward = true;
        private Sprite sprite;

        public SpriteAnimationTask(Sprite sprite, boolean forward) {
            this.sprite = sprite;
            this.forward = forward;
        }

        public void run() {
            if (!this.moving) {
                return;
            }
            
            if (this.forward) {
                this.sprite.nextFrame();
            } else {
                this.sprite.prevFrame();
            }
        }

        public void forward() {
            this.forward = true;
            this.moving = true;
        }

        public void backward() {
            this.forward = false;
            this.moving = true;
        }

        public void setMoving(boolean isMoving) {
            this.moving = isMoving;
        }
    }
}
